{% extends 'base.html' %}
{% load static %}

{% block title %}发现活动 - 本地有约{% endblock %}

{% block content %}
<style>
    :root {
        --primary-color: #7F9F7F;      /* 柔和的灰绿色 */
        --secondary-color: #A8C0A8;    /* 浅灰绿 */
        --accent-color: #D4E8D4;       /* 更浅的灰绿 */
        --light-color: #F8FBF8;        /* 极浅灰绿背景 */
        --dark-color: #5A735A;         /* 深灰绿 */
        --text-primary: #2C3E2C;       /* 深绿文字 */
        --text-secondary: #6B7A6B;     /* 中灰绿文字 */
        --border-color: #E1E8E1;       /* 边框灰绿 */
    }

    body {
        background-color: var(--light-color);
        font-family: 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', sans-serif;
        color: var(--text-primary);
        line-height: 1.6;
    }

    .bg-primary { background-color: var(--primary-color) !important; }
    .text-primary { color: var(--primary-color) !important; }
    .btn-primary {
        background-color: var(--primary-color);
        border-color: var(--primary-color);
        color: white;
        transition: all 0.3s ease;
    }
    .btn-primary:hover {
        background-color: var(--dark-color);
        border-color: var(--dark-color);
        transform: translateY(-1px);
    }

    .btn-outline-primary {
        color: var(--primary-color);
        border-color: var(--primary-color);
        transition: all 0.3s ease;
    }
    .btn-outline-primary:hover {
        background-color: var(--primary-color);
        border-color: var(--primary-color);
        color: white;
    }

    /* 重新设计的活动卡片 */
    .activity-card {
        transition: all 0.3s ease;
        border: 1px solid var(--border-color);
        border-radius: 16px;
        background: white;
        box-shadow: 0 4px 12px rgba(127, 159, 127, 0.08);
        overflow: hidden;
        height: 100%;
    }

    .activity-card:hover {
        transform: translateY(-4px);
        box-shadow: 0 12px 28px rgba(127, 159, 127, 0.15);
        border-color: var(--accent-color);
    }

    .activity-image-container {
        position: relative;
        height: 180px;
        overflow: hidden;
    }

    .activity-image {
        width: 100%;
        height: 100%;
        object-fit: cover;
        transition: transform 0.5s ease;
    }

    .activity-card:hover .activity-image {
        transform: scale(1.05);
    }

    .activity-badge {
        position: absolute;
        top: 12px;
        left: 12px;
        font-size: 0.75rem;
        background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
        color: white;
        border: none;
        padding: 6px 12px;
        border-radius: 20px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    }

    .activity-content {
        padding: 20px;
        display: flex;
        flex-direction: column;
        height: calc(100% - 180px);
    }

    .activity-title {
        font-size: 1.1rem;
        font-weight: 600;
        margin-bottom: 8px;
        color: var(--text-primary);
        line-height: 1.4;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
    }

    .activity-meta {
        display: flex;
        align-items: center;
        margin-bottom: 12px;
        color: var(--text-secondary);
        font-size: 0.85rem;
    }

    .activity-meta i {
        margin-right: 4px;
    }

    .activity-description {
        color: var(--text-secondary);
        font-size: 0.9rem;
        margin-bottom: 16px;
        flex-grow: 1;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
    }

    .activity-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: auto;
    }

    .activity-organizer {
        display: flex;
        align-items: center;
    }

    .organizer-avatar {
        width: 32px;
        height: 32px;
        border-radius: 50%;
        background: linear-gradient(135deg, var(--accent-color), var(--light-color));
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 8px;
        border: 2px solid var(--border-color);
        transition: border-color 0.3s ease;
    }

    .organizer-avatar:hover {
        border-color: var(--primary-color);
    }

    .organizer-name {
        font-size: 0.85rem;
        color: var(--text-secondary);
    }

    .activity-stats {
        display: flex;
        align-items: center;
    }

    .rating-stars {
        color: #FFB74D;
        margin-right: 8px;
    }

    .participant-count {
        background: var(--accent-color);
        color: var(--text-primary);
        border-radius: 12px;
        padding: 4px 10px;
        font-size: 0.8rem;
    }

    /* 地图容器 - 默认隐藏 */
    .map-container {
        height: 500px;
        background: linear-gradient(135deg, var(--light-color), var(--accent-color));
        border-radius: 12px;
        margin-bottom: 20px;
        border: 1px solid var(--border-color);
        overflow: hidden;
        display: none; /* 默认隐藏 */
    }

    /* 活动列表容器 - 默认显示 */
    .activity-list-container {
        display: block; /* 默认显示 */
    }

    /* 筛选区域 */
    .filter-section {
        background: white;
        border-radius: 12px;
        padding: 16px;
        margin-bottom: 20px;
        box-shadow: 0 2px 8px rgba(127, 159, 127, 0.08);
        border: 1px solid var(--border-color);
    }

    .filter-scroll {
        overflow-x: auto;
        white-space: nowrap;
        -ms-overflow-style: none;
        scrollbar-width: none;
        padding-bottom: 8px;
    }

    .filter-scroll::-webkit-scrollbar {
        display: none;
    }

    .filter-btn {
        border-radius: 20px;
        padding: 8px 16px;
        margin-right: 8px;
        transition: all 0.3s ease;
        border: 1px solid var(--border-color);
        background: white;
        color: var(--text-secondary);
    }

    .filter-btn.active {
        background-color: var(--primary-color);
        border-color: var(--primary-color);
        color: white;
    }

    .filter-btn:hover:not(.active) {
        background-color: var(--accent-color);
        border-color: var(--primary-color);
    }

    /* 搜索栏 */
    .search-container {
        position: relative;
        margin-bottom: 20px;
    }

    .search-box {
        border-radius: 50px;
        box-shadow: 0 2px 15px rgba(127, 159, 127, 0.1);
        border: 1px solid var(--border-color);
        overflow: hidden;
        background: white;
    }

    .search-box:focus-within {
        box-shadow: 0 4px 20px rgba(127, 159, 127, 0.2);
        border-color: var(--primary-color);
    }

    /* 位置指示器 */
    .location-indicator {
        background: white;
        border: 1px solid var(--border-color);
        border-radius: 12px;
        padding: 12px 16px;
        margin-bottom: 20px;
        box-shadow: 0 2px 8px rgba(127, 159, 127, 0.08);
    }

    /* 导航栏覆盖 */
    .navbar-custom {
        background: rgba(255, 255, 255, 0.95);
        backdrop-filter: blur(10px);
        box-shadow: 0 2px 20px rgba(127, 159, 127, 0.1);
        border-bottom: 1px solid var(--border-color);
    }

    /* 页脚覆盖 */
    .footer-custom {
        background: linear-gradient(135deg, var(--dark-color), var(--text-primary));
        color: white;
    }

    /* 分页样式 */
    .pagination-custom .page-link {
        color: var(--primary-color);
        border: 1px solid var(--border-color);
        margin: 0 4px;
        border-radius: 8px;
        transition: all 0.3s ease;
    }

    .pagination-custom .page-link:hover {
        background-color: var(--primary-color);
        border-color: var(--primary-color);
        color: white;
    }

    .pagination-custom .page-item.active .page-link {
        background-color: var(--primary-color);
        border-color: var(--primary-color);
    }

    /* 视图切换 */
    .view-toggle .btn {
        border-radius: 12px;
        padding: 8px 20px;
        transition: all 0.3s ease;
    }

    /* 加载动画 */
    .loading-overlay {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(255, 255, 255, 0.8);
        display: none;
        justify-content: center;
        align-items: center;
        z-index: 9999;
    }

    .loading-spinner {
        width: 50px;
        height: 50px;
        border: 5px solid var(--accent-color);
        border-top: 5px solid var(--primary-color);
        border-radius: 50%;
        animation: spin 1s linear infinite;
    }

    @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }

    /* 响应式调整 */
    @media (max-width: 768px) {
        .activity-image-container {
            height: 160px;
        }

        .activity-content {
            padding: 16px;
        }

        .map-container {
            height: 400px;
        }
    }

    /* 地图视图样式 */
    .map-view .map-container {
        display: block;
    }

    .map-view .activity-list-container {
        display: none;
    }

    .list-view .map-container {
        display: none;
    }

    .list-view .activity-list-container {
        display: block;
    }

    /* 视图切换按钮激活状态 */
    .view-toggle .btn.active {
        background-color: var(--primary-color);
        border-color: var(--primary-color);
        color: white;
    }

    .view-toggle .btn:not(.active) {
        background-color: white;
        border-color: var(--border-color);
        color: var(--text-secondary);
    }

    /* 地图控制按钮样式 */
    .map-controls .btn {
        border-radius: 8px;
        width: 40px;
        height: 40px;
        display: flex;
        align-items: center;
        justify-content: center;
        box-shadow: 0 2px 8px rgba(0,0,0,0.2);
    }

    /* 加载状态 */
    .search-loading {
        position: relative;
    }

    .search-loading::after {
        content: '';
        position: absolute;
        right: 10px;
        top: 50%;
        transform: translateY(-50%);
        width: 16px;
        height: 16px;
        border: 2px solid var(--border-color);
        border-top: 2px solid var(--primary-color);
        border-radius: 50%;
        animation: spin 1s linear infinite;
    }
</style>

<!-- 加载遮罩 -->
<div class="loading-overlay" id="loadingOverlay">
    <div class="loading-spinner"></div>
</div>

<div class="container py-4">
    <!-- 页面标题和创建按钮 -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h2 class="mb-1" style="color: var(--text-primary);">发现活动</h2>
            <p class="text-muted mb-0">探索您附近的有趣活动</p>
        </div>
        <a href="{% url 'location:activity_create' %}" class="btn btn-primary rounded-pill px-4">
            <i class="fas fa-plus me-2"></i>创建活动
        </a>
    </div>

    <!-- 搜索栏 -->
    <div class="search-container">
        <div class="input-group input-group-lg search-box">
            <span class="input-group-text bg-white border-end-0" style="border: none;">
                <i class="fas fa-search" style="color: var(--text-secondary);"></i>
            </span>
            <input type="text" class="form-control border-start-0" id="searchInput" placeholder="搜索活动、地点或关键词..." style="border: none;">
            <button class="btn btn-outline-secondary border-start-0" type="button" style="border: none;">
                <i class="fas fa-sliders-h" style="color: var(--text-secondary);"></i>
            </button>
        </div>
    </div>

    <!-- 筛选区域 -->
    <div class="filter-section">
        <h6 class="mb-3" style="color: var(--text-primary);">筛选活动</h6>
        <div class="filter-scroll" id="category-filter-container">
            <!-- 动态生成分类筛选按钮 -->
            <button class="filter-btn active" data-category="">🏷️ 全部</button>
            {% for category in categories %}
            <button class="filter-btn" data-category="{{ category.id }}">
                {% if category.icon and category.icon|length > 1 %}{{ category.icon }}{% else %}🏷️{% endif %} {{ category.name }}
            </button>
            {% empty %}
            <button class="filter-btn" data-category="1">🏷️ 默认分类</button>
            {% endfor %}
        </div>
    </div>

    <!-- 位置和视图切换 -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div class="location-indicator d-flex align-items-center">
            <i class="fas fa-map-marker-alt me-2" style="color: var(--primary-color);"></i>
            <span class="fw-medium" style="color: var(--text-primary);">北京市朝阳区</span>
            <i class="fas fa-chevron-down ms-2" style="color: var(--text-secondary);"></i>
        </div>
        <div class="btn-group view-toggle" role="group">
            <button type="button" class="btn active rounded-pill" data-view="list">
                <i class="fas fa-list me-2"></i>列表
            </button>
            <button type="button" class="btn rounded-pill" data-view="map">
                <i class="fas fa-map me-2"></i>地图
            </button>
        </div>
    </div>

    <!-- 地图区域 -->
    <div class="card border-0 shadow-sm mb-4">
        <div class="card-body p-0">
            <div id="map-container" class="map-container">
                <div class="d-flex justify-content-center align-items-center h-100">
                    <div class="text-center">
                        <i class="fas fa-map-marked-alt fa-3x mb-3" style="color: var(--primary-color);"></i>
                        <h5 class="text-muted mb-3">活动地图</h5>
                        <p class="text-muted mb-3">在地图上查看活动位置分布</p>
                        <button class="btn btn-outline-primary rounded-pill px-4" onclick="switchToListView()">
                            <i class="fas fa-list me-2"></i>切换到列表视图
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 活动统计 -->
    <div class="d-flex justify-content-between align-items-center mb-3">
        <h5 class="mb-0" style="color: var(--text-primary);">附近活动</h5>
        <span class="text-muted" id="activityCount">找到 24 个活动</span>
    </div>

    <!-- 活动列表容器 -->
    <div id="activity-list-container" class="activity-list-container">
        <!-- 活动列表将通过 AJAX 加载 -->
        <div class="row" id="activity-list">
            <!-- 活动卡片将通过 AJAX 动态加载 -->
        </div>

        <!-- 分页 -->
        <div class="row mt-5">
            <div class="col-12">
                <nav aria-label="活动分页">
                    <ul class="pagination pagination-custom justify-content-center" id="pagination">
                        <!-- 分页将通过 AJAX 动态生成 -->
                    </ul>
                </nav>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script src="https://api.map.baidu.com/api?v=3.0&ak=rUiyl00fneDC8rieZJagiXxwyDl7ZYje"></script>
<script>
// 全局变量存储当前状态
let currentState = {
    page: 1,
    category: '',
    search: '',
    sort: 'start_time',
    time: ''
};

// 地图相关全局变量
let currentMap = null;
let userLocation = null;
let activityMarkers = [];

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    // 从 URL 初始化状态
    initStateFromURL();

    // 初始加载活动数据
    loadActivities();

    // 初始化用户位置
    initUserLocation();

    // 视图切换功能
    const viewToggleBtns = document.querySelectorAll('.view-toggle .btn');

    viewToggleBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            const viewType = this.getAttribute('data-view');

            // 切换按钮激活状态
            viewToggleBtns.forEach(b => b.classList.remove('active'));
            this.classList.add('active');

            // 切换视图
            if (viewType === 'map') {
                switchToMapView();
            } else {
                switchToListView();
            }
        });
    });

    // 筛选按钮激活状态
    const filterBtns = document.querySelectorAll('.filter-btn');
    filterBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            filterBtns.forEach(b => b.classList.remove('active'));
            this.classList.add('active');

            // 更新分类筛选并重新加载
            currentState.category = this.dataset.category;
            currentState.page = 1; // 重置到第一页
            loadActivities();
        });
    });

    // 搜索功能
    const searchInput = document.getElementById('searchInput');
    let searchTimeout;

    searchInput.addEventListener('input', function() {
        clearTimeout(searchTimeout);
        searchTimeout = setTimeout(() => {
            currentState.search = this.value;
            currentState.page = 1; // 重置到第一页
            loadActivities();
        }, 500); // 500ms 防抖
    });

    // 图片加载错误处理
    document.addEventListener('error', function(e) {
        if (e.target.tagName === 'IMG') {
            e.target.style.display = 'none';
            const placeholder = e.target.nextElementSibling;
            if (placeholder && placeholder.classList.contains('placeholder')) {
                placeholder.style.display = 'flex';
            }
        }
    }, true);
});

// 初始化用户位置
function initUserLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
            function(position) {
                userLocation = {
                    lat: position.coords.latitude,
                    lng: position.coords.longitude
                };

                // 存储用户位置
                localStorage.setItem('userLocation', JSON.stringify(userLocation));

                // 更新位置显示
                updateLocationDisplay(userLocation);

                // 如果有地图视图，更新地图中心
                if (document.body.classList.contains('map-view') && currentMap) {
                    updateMapCenter(userLocation);
                }
            },
            function(error) {
                console.log('获取位置失败:', error);
                // 使用默认位置
                userLocation = { lat: 34.806070, lng: 113.666448 };
                localStorage.setItem('userLocation', JSON.stringify(userLocation));
                updateLocationDisplay(userLocation);
            },
            {
                enableHighAccuracy: true,
                timeout: 10000,
                maximumAge: 600000
            }
        );
    } else {
        console.log('浏览器不支持地理位置服务');
        userLocation = { lat: 39.9042, lng: 116.4074 };
        updateLocationDisplay(userLocation);
    }
}

// 更新位置显示
function updateLocationDisplay(location) {
    const locationElement = document.querySelector('.location-indicator span');
    if (locationElement) {
        // 这里可以调用逆地理编码服务获取具体地址
        // 暂时显示坐标
        locationElement.textContent = `当前位置 (${location.lat.toFixed(4)}, ${location.lng.toFixed(4)})`;
    }
}

// 切换到地图视图
function switchToMapView() {
    document.body.classList.remove('list-view');
    document.body.classList.add('map-view');
    initMap();
}

// 切换到列表视图
function switchToListView() {
    document.body.classList.remove('map-view');
    document.body.classList.add('list-view');

    // 更新按钮状态
    document.querySelector('.view-toggle .btn[data-view="list"]').classList.add('active');
    document.querySelector('.view-toggle .btn[data-view="map"]').classList.remove('active');
}

// 初始化地图
function initMap() {
    console.log('初始化地图...');
    const mapContainer = document.getElementById('map-container');

    // 获取用户位置
    const savedLocation = localStorage.getItem('userLocation');
    const centerLocation = savedLocation ? JSON.parse(savedLocation) : { lat: 39.9042, lng: 116.4074 };

    mapContainer.innerHTML = `
        <div id="map" style="width: 100%; height: 100%;"></div>
        <div class="map-controls" style="position: absolute; top: 10px; right: 10px; z-index: 1000;">
            <button class="btn btn-primary btn-sm mb-2" onclick="locateUser()" title="定位到我的位置">
                <i class="fas fa-location-arrow"></i>
            </button>
            <br>
            <button class="btn btn-light btn-sm" onclick="switchToListView()" title="切换到列表视图">
                <i class="fas fa-list"></i>
            </button>
        </div>
    `;

    // 初始化百度地图
    initializeBaiduMap(centerLocation);
}

// 初始化百度地图
function initializeBaiduMap(center) {
    // 创建地图实例
    currentMap = new BMap.Map("map");
    const point = new BMap.Point(center.lng, center.lat);
    currentMap.centerAndZoom(point, 13);
    currentMap.enableScrollWheelZoom(true);

    // 添加基本控件
    currentMap.addControl(new BMap.NavigationControl());
    currentMap.addControl(new BMap.ScaleControl());

    // 添加用户位置标记
    addUserLocationMarker();

    // 加载活动标记
    loadActivitiesForMap();
}

// 添加用户位置标记
function addUserLocationMarker() {
    if (!currentMap || !userLocation) return;

    const point = new BMap.Point(userLocation.lng, userLocation.lat);
    const marker = new BMap.Marker(point);

    // 自定义用户位置标记的样式
    marker.setIcon(new BMap.Icon(
        'http://api.map.baidu.com/images/geolocation_control.png',
        new BMap.Size(25, 34),
        {anchor: new BMap.Size(12, 34)}
    ));

    const infoWindow = new BMap.InfoWindow("您的位置", {
        width: 100,
        height: 40
    });

    marker.addEventListener("click", function() {
        this.openInfoWindow(infoWindow);
    });

    currentMap.addOverlay(marker);
}

// 为地图加载活动数据
function loadActivitiesForMap() {
    if (!currentMap) return;

    const params = new URLSearchParams();
    if (currentState.category) params.append('category', currentState.category);
    if (currentState.search) params.append('search', currentState.search);
    if (currentState.time) params.append('time', currentState.time);

    const savedLocation = localStorage.getItem('userLocation');
    if (savedLocation) {
        const location = JSON.parse(savedLocation);
        params.append('lat', location.lat);
        params.append('lng', location.lng);
    }

    params.append('ajax', 'true');

    fetch(`/location/activities/?${params.toString()}`, {
        headers: {
            'X-Requested-With': 'XMLHttpRequest',
            'Accept': 'application/json'
        }
    })
    .then(response => response.json())
    .then(data => {
        updateMapMarkers(data.activities);
    })
    .catch(error => {
        console.error('加载地图活动数据失败:', error);
    });
}

// 更新地图标记
function updateMapMarkers(activities) {
    if (!currentMap || !activities) return;

    // 清除现有活动标记
    activityMarkers.forEach(marker => {
        currentMap.removeOverlay(marker);
    });
    activityMarkers = [];

    // 为每个活动添加标记
    activities.forEach(activity => {
        if (activity.latitude && activity.longitude) {
            const point = new BMap.Point(activity.longitude, activity.latitude);
            const marker = new BMap.Marker(point);

            // 使用真实时间显示
            const timeDisplay = activity.start_time_display || formatDate(activity.start_time);

            // 创建信息窗口内容
            const content = `
                <div class="map-marker-popup" style="min-width: 250px;">
                    <img src="${activity.image_url}" alt="${activity.title}"
                         style="width: 100%; height: 120px; object-fit: cover; border-radius: 8px; margin-bottom: 8px;"
                         onerror="this.src='https://images.unsplash.com/photo-1546519638-68e109498ffc?ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60'">
                    <h6 style="margin-bottom: 8px; font-weight: 600;">${activity.title}</h6>
                    <p style="margin-bottom: 4px; font-size: 12px; color: #666;">
                        <i class="fas fa-tag"></i> ${activity.category.name}
                    </p>
                    <p style="margin-bottom: 4px; font-size: 12px; color: #666;">
                        <i class="fas fa-map-marker-alt"></i> ${activity.distance}
                    </p>
                    <p style="margin-bottom: 8px; font-size: 12px; color: #666;">
                        <i class="far fa-clock"></i> ${timeDisplay}
                    </p>
                    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px;">
                        <div style="color: #FFB74D;">
                            ⭐ ${activity.rating.toFixed(1)}
                        </div>
                        <span style="background: var(--accent-color); color: var(--text-primary);
                                   border-radius: 12px; padding: 4px 8px; font-size: 12px;">
                            ${activity.participant_count}/${activity.max_participants}人
                        </span>
                    </div>
                    <button class="btn btn-primary btn-sm w-100"
                            onclick="window.location.href='/location/activity_detail/${activity.id}/'">
                        查看详情
                    </button>
                </div>
            `;

            const infoWindow = new BMap.InfoWindow(content, {
                width: 280,
                height: 320
            });

            marker.addEventListener("click", function() {
                this.openInfoWindow(infoWindow);
            });

            currentMap.addOverlay(marker);
            activityMarkers.push(marker);
        }
    });

    // 调整地图视野以包含所有标记
    if (activityMarkers.length > 0) {
        const bounds = currentMap.getBounds();
        activityMarkers.forEach(marker => {
            bounds.extend(marker.getPosition());
        });
        currentMap.setViewport(bounds);
    }
}

// 定位用户位置
function locateUser() {
    if (navigator.geolocation && currentMap) {
        navigator.geolocation.getCurrentPosition(
            function(position) {
                userLocation = {
                    lat: position.coords.latitude,
                    lng: position.coords.longitude
                };

                // 更新地图中心
                const point = new BMap.Point(userLocation.lng, userLocation.lat);
                currentMap.centerAndZoom(point, 15);

                // 更新本地存储
                localStorage.setItem('userLocation', JSON.stringify(userLocation));
                updateLocationDisplay(userLocation);

                // 重新加载活动数据（基于新位置）
                loadActivities();
            },
            function(error) {
                alert('无法获取您的位置信息：' + getLocationErrorText(error));
            }
        );
    }
}

// 获取位置错误信息
function getLocationErrorText(error) {
    switch(error.code) {
        case error.PERMISSION_DENIED:
            return '用户拒绝位置请求';
        case error.POSITION_UNAVAILABLE:
            return '位置信息不可用';
        case error.TIMEOUT:
            return '位置请求超时';
        default:
            return '未知错误';
    }
}

// 更新地图中心
function updateMapCenter(location) {
    if (currentMap) {
        const point = new BMap.Point(location.lng, location.lat);
        currentMap.panTo(point);
    }
}

// 加载活动数据
function loadActivities() {
    showLoading();

    // 构建查询参数
    const params = new URLSearchParams();
    if (currentState.page) params.append('page', currentState.page);
    if (currentState.category) params.append('category', currentState.category);
    if (currentState.search) params.append('search', currentState.search);
    if (currentState.sort) params.append('sort', currentState.sort);
    if (currentState.time) params.append('time', currentState.time);

    // 添加 ajax 参数用于标识 AJAX 请求
    params.append('ajax', 'true');

    // 获取用户位置信息
    const savedLocation = localStorage.getItem('userLocation');
    if (savedLocation) {
        const location = JSON.parse(savedLocation);
        params.append('lat', location.lat);
        params.append('lng', location.lng);
    }

    // 修复：使用正确的 URL 路径
    const apiUrl = `/location/activities/?${params.toString()}`;

    console.log('正在请求:', apiUrl);

    // 发送 AJAX 请求
    fetch(apiUrl, {
        headers: {
            'X-Requested-With': 'XMLHttpRequest',
            'Accept': 'application/json'
        }
    })
    .then(response => {
        if (!response.ok) {
            throw new Error(`网络响应不正常: ${response.status} ${response.statusText}`);
        }
        return response.json();
    })
    .then(data => {
        console.log('收到数据:', data);
        updateActivityList(data.activities);
        updatePagination(data.pagination);
        updateActivityCount(data.total_activities);
        updateURL();
        hideLoading();

        // 如果在地图视图，更新地图标记
        if (document.body.classList.contains('map-view')) {
            updateMapMarkers(data.activities);
        }
    })
    .catch(error => {
        console.error('加载活动数据失败:', error);
        hideLoading();

        // 显示更友好的错误信息
        const activityList = document.getElementById('activity-list');
        activityList.innerHTML = `
            <div class="col-12 text-center py-5">
                <i class="fas fa-exclamation-triangle fa-3x mb-3" style="color: var(--text-secondary);"></i>
                <h5 class="text-muted">加载活动数据失败</h5>
                <p class="text-muted">${error.message}</p>
                <button class="btn btn-primary rounded-pill px-4 mt-2" onclick="loadActivities()">
                    <i class="fas fa-redo me-2"></i>重新加载
                </button>
            </div>
        `;
    });
}

// 更新活动列表
function updateActivityList(activities) {
    const activityList = document.getElementById('activity-list');

    if (!activities || activities.length === 0) {
        activityList.innerHTML = `
            <div class="col-12 text-center py-5">
                <i class="fas fa-search fa-3x mb-3" style="color: var(--text-secondary);"></i>
                <h5 class="text-muted">没有找到相关活动</h5>
                <p class="text-muted">尝试调整搜索条件或筛选条件</p>
                <button class="btn btn-outline-primary rounded-pill px-4 mt-2" onclick="resetFilters()">
                    <i class="fas fa-refresh me-2"></i>重置筛选
                </button>
            </div>
        `;
        return;
    }

    let html = '';
    activities.forEach(activity => {
        // 处理可能缺失的数据
        const category = activity.category || { icon: '🏷️', name: '未分类' };
        const organizer = activity.organizer || { username: '未知组织者' };

        // 使用后端返回的image_url，后端已经处理好了OSS URL或默认图片
        const imageUrl = activity.image_url;
        const description = activity.description || '暂无描述';

        // 使用真实距离数据
        const distance = activity.distance || '距离未知';

        // 使用真实时间显示
        const timeDisplay = activity.start_time_display || formatDate(activity.start_time);

        const rating = activity.rating || 0;
        const participantCount = activity.participant_count || 0;
        const maxParticipants = activity.max_participants || 0;

        html += `
            <div class="col-md-6 col-lg-4 mb-4">
                <div class="card activity-card h-100" onclick="window.location.href='/location/activity_detail/${activity.id}/'" style="cursor: pointer;">
                    <div class="activity-image-container">
                        <img src="${imageUrl}"
                             class="activity-image"
                             alt="${activity.title}"
                             onerror="handleImageError(this, ${activity.has_custom_image || false})">
                        <div class="activity-image placeholder d-flex align-items-center justify-content-center bg-light" style="display: none; background: linear-gradient(135deg, var(--accent-color), var(--light-color));">
                            <i class="fas fa-calendar-alt fa-2x" style="color: var(--text-secondary);"></i>
                        </div>
                        <span class="activity-badge">${category.icon} ${category.name}</span>
                    </div>
                    <div class="activity-content">
                        <h5 class="activity-title">${activity.title}</h5>
                        <div class="activity-meta">
                            <i class="far fa-clock me-1"></i>
                            <span>${timeDisplay}</span>
                            <i class="fas fa-map-marker-alt ms-3 me-1"></i>
                            <span>${distance}</span>
                        </div>
                        <p class="activity-description">${truncateText(description, 80)}</p>
                        <div class="activity-footer">
                            <div class="activity-organizer">
                                <div class="organizer-avatar">
                                    <i class="fas fa-user" style="color: var(--text-secondary); font-size: 0.8rem;"></i>
                                </div>
                                <span class="organizer-name">${organizer.username}</span>
                            </div>
                            <div class="activity-stats">
                                <div class="rating-stars">
                                    <i class="fas fa-star"></i>
                                    <span>${rating.toFixed(1)}</span>
                                </div>
                                <span class="participant-count">${participantCount}/${maxParticipants}</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `;
    });

    activityList.innerHTML = html;
}

// formatDate 函数
function formatDate(dateString) {
    const date = new Date(dateString);
    const now = new Date();
    const diffInHours = Math.floor((date - now) / (1000 * 60 * 60));
    const diffInDays = Math.floor(diffInHours / 24);

    if (diffInHours < 0) {
        // 活动已开始
        const hoursAgo = Math.abs(diffInHours);
        if (hoursAgo < 24) {
            return "今天";
        } else if (hoursAgo < 48) {
            return "昨天";
        } else if (hoursAgo < 168) {
            return `${Math.floor(hoursAgo / 24)}天前`;
        } else {
            return date.toLocaleDateString('zh-CN', { month: 'short', day: 'numeric' });
        }
    } else {
        // 活动未开始
        if (diffInHours < 24) {
            if (diffInHours < 1) {
                const minutes = Math.floor((date - now) / (1000 * 60));
                return minutes > 0 ? `${minutes}分钟后` : "即将开始";
            }
            return `${diffInHours}小时后`;
        } else if (diffInDays === 1) {
            return "明天";
        } else if (diffInDays < 7) {
            return `${diffInDays}天后`;
        } else {
            return date.toLocaleDateString('zh-CN', {
                month: 'short',
                day: 'numeric',
                hour: '2-digit',
                minute: '2-digit'
            });
        }
    }
}

// 添加图片错误处理函数
function handleImageError(imgElement, hasCustomImage) {
    console.log('图片加载失败:', imgElement.src, '有自定义图片:', hasCustomImage);

    if (hasCustomImage) {
        // 如果有自定义图片但加载失败，重试一次（可能是网络问题）
        const originalSrc = imgElement.src;
        // 添加时间戳避免缓存
        imgElement.src = originalSrc + (originalSrc.includes('?') ? '&' : '?') + 'retry=' + new Date().getTime();
        imgElement.onerror = function() {
            // 第二次失败，显示占位符
            showPlaceholder(imgElement);
        };
    } else {
        // 没有自定义图片，直接显示占位符
        showPlaceholder(imgElement);
    }
}

function showPlaceholder(imgElement) {
    const placeholder = imgElement.nextElementSibling;
    if (placeholder && placeholder.classList.contains('placeholder')) {
        placeholder.style.display = 'flex';
    }
    imgElement.style.display = 'none';
}

// 更新分页
function updatePagination(pagination) {
    const paginationElement = document.getElementById('pagination');
    if (!pagination || !paginationElement) return;

    const { current_page, total_pages, has_previous, has_next } = pagination;
    let html = '';

    // 上一页
    if (has_previous) {
        html += `
            <li class="page-item">
                <a class="page-link" href="#" onclick="changePage(${current_page - 1}); return false;">
                    <i class="fas fa-chevron-left"></i>
                </a>
            </li>
        `;
    } else {
        html += `
            <li class="page-item disabled">
                <span class="page-link"><i class="fas fa-chevron-left"></i></span>
            </li>
        `;
    }

    // 页码
    const startPage = Math.max(1, current_page - 2);
    const endPage = Math.min(total_pages, current_page + 2);

    for (let i = startPage; i <= endPage; i++) {
        if (i === current_page) {
            html += `
                <li class="page-item active">
                    <span class="page-link">${i}</span>
                </li>
            `;
        } else {
            html += `
                <li class="page-item">
                    <a class="page-link" href="#" onclick="changePage(${i}); return false;">${i}</a>
                </li>
            `;
        }
    }

    // 下一页
    if (has_next) {
        html += `
            <li class="page-item">
                <a class="page-link" href="#" onclick="changePage(${current_page + 1}); return false;">
                    <i class="fas fa-chevron-right"></i>
                </a>
            </li>
        `;
    } else {
        html += `
            <li class="page-item disabled">
                <span class="page-link"><i class="fas fa-chevron-right"></i></span>
            </li>
        `;
    }

    paginationElement.innerHTML = html;
}

// 更新活动计数
function updateActivityCount(count) {
    const countElement = document.getElementById('activityCount');
    if (countElement) {
        countElement.textContent = `找到 ${count} 个活动`;
    }
}

// 改变页码
function changePage(page) {
    currentState.page = page;
    loadActivities();
}

// 重置筛选
function resetFilters() {
    currentState = {
        page: 1,
        category: '',
        search: '',
        sort: 'start_time',
        time: ''
    };

    // 重置筛选按钮状态
    const filterBtns = document.querySelectorAll('.filter-btn');
    filterBtns.forEach(btn => {
        btn.classList.remove('active');
        if (btn.dataset.category === '') {
            btn.classList.add('active');
        }
    });

    // 重置搜索框
    const searchInput = document.getElementById('searchInput');
    if (searchInput) {
        searchInput.value = '';
    }

    loadActivities();
}

// 截断文本
function truncateText(text, maxLength) {
    if (text.length <= maxLength) return text;
    return text.substring(0, maxLength) + '...';
}

// 显示加载状态
function showLoading() {
    const overlay = document.getElementById('loadingOverlay');
    if (overlay) {
        overlay.style.display = 'flex';
    }
}

// 隐藏加载状态
function hideLoading() {
    const overlay = document.getElementById('loadingOverlay');
    if (overlay) {
        overlay.style.display = 'none';
    }
}

// 从 URL 初始化状态
function initStateFromURL() {
    const urlParams = new URLSearchParams(window.location.search);
    currentState.page = parseInt(urlParams.get('page')) || 1;
    currentState.category = urlParams.get('category') || '';
    currentState.search = urlParams.get('search') || '';
    currentState.sort = urlParams.get('sort') || 'start_time';
    currentState.time = urlParams.get('time') || '';

    // 更新筛选按钮状态
    const filterBtns = document.querySelectorAll('.filter-btn');
    filterBtns.forEach(btn => {
        btn.classList.remove('active');
        if (btn.dataset.category === currentState.category) {
            btn.classList.add('active');
        }
    });

    // 更新搜索框
    const searchInput = document.getElementById('searchInput');
    if (searchInput && currentState.search) {
        searchInput.value = currentState.search;
    }
}

// 更新 URL（不刷新页面）
function updateURL() {
    const params = new URLSearchParams();
    if (currentState.page > 1) params.append('page', currentState.page);
    if (currentState.category) params.append('category', currentState.category);
    if (currentState.search) params.append('search', currentState.search);
    if (currentState.sort !== 'start_time') params.append('sort', currentState.sort);
    if (currentState.time) params.append('time', currentState.time);

    const newURL = `${window.location.pathname}?${params.toString()}`;
    window.history.replaceState(null, '', newURL);
}
</script>
{% endblock %}